import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/location_repository/location_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/company/choose_city/choose_city_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_address_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/company_branch_bean.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_address/punch_rule_location_page.dart';
import 'package:e_reception_flutter/ui/company/company_register/bean/company_register_upload_bean.dart';
import 'package:e_reception_flutter/utils/address_about_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';

import '../company_basic_data_view_model.dart';
import 'company_branch_detail_view_model.dart';

class CompanyCreateOrEditBranchPage extends StatefulWidget {
  final String pageType;
  final CompanyBranchListInfoBean itemBean;
  final VoidCallback voidCallback;
  final String defauleGps;
  final String companyNick;
  final Function(CompanyBranchListInfoBean itemBean) updateBranch;
  final int size;
  const CompanyCreateOrEditBranchPage({Key key, this.pageType,
    this.itemBean, this.voidCallback, this.defauleGps,
    this.companyNick, this.updateBranch, this.size}) : super(key: key);

  static const String ROUTER = "CompanyCreateOrEditBranchPage";

  @override
  _CompanyCreateOrEditBranchPageState createState() => _CompanyCreateOrEditBranchPageState();

  static Future<dynamic> navigatorPush(BuildContext context, String pageType, CompanyBranchListInfoBean itemBean,
      String defauleGps, String companyNick, VoidCallback voidCallback, {Function updateBranch, int size}) {
    return RouterUtils.routeForFutureResult(
      context,
      CompanyCreateOrEditBranchPage(
          pageType: pageType,
          itemBean: itemBean,
          defauleGps: defauleGps,
          companyNick: companyNick,
          voidCallback: voidCallback,
          updateBranch: updateBranch,
          size: size
      ),
      routeName: CompanyCreateOrEditBranchPage.ROUTER,
    );
  }
}

class _CompanyCreateOrEditBranchPageState extends BaseState<CompanyCreateOrEditBranchPage> {
  TextEditingController _editingBranchNameController;

  TextEditingController _locationEditingController;

  TextEditingController _locationAddressController;

  CompanyRegisterUploadBean _uploadBean;
  Map<String, ChooseCityListItemBean> _resultLocationMap;

  TextEditingController _editingAddressController;

  VgLocation _locationPlugin;

  CompanyBranchDetailViewModel viewModel;

  String province;
  String city ;
  String dirstrict;

  bool buttonFull = false;

  String gps;

  String addrCode;

  String gpsadress;

  String branchName;

  var  lastPopTime;

  @override
  void initState() {
    super.initState();
    lastPopTime = DateTime.now().add(Duration(minutes: -1));
    viewModel = CompanyBranchDetailViewModel(this);
    _locationEditingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _editingAddressController = TextEditingController()
      ..addListener(() => _notifyChange());
    _editingBranchNameController = TextEditingController()
      ..addListener(() => _notifyChange());
    _locationAddressController = TextEditingController()
      ..addListener(() => _notifyChange());
    if(widget?.itemBean == null && widget?.pageType == "新增"){
      _initLocation();
    }else{
      _setBranchName();
      _setLocationEditingValue();
      _setAddressGps();
    }
  }

  _initLocation(){
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocationWithoutCheckPermission((locationMap) {
      print("能不能收到");
      var transResult = VgLocationUtils.transLocationToMap(locationMap);
      if (transResult == null) {
        _resultLocationMap = {
          CHOOSE_PROVINCE_KEY:
          ChooseCityListItemBean("110000", "北京市"),
          CHOOSE_CITY_KEY: ChooseCityListItemBean("110100", "北京市"),
          CHOOSE_DISTRICT_KEY:
          ChooseCityListItemBean("110101", "东城区", latitude: 39.917544, longitude: 116.418757)
        };
      }else{
        _resultLocationMap = transResult;
      }
      _setBranchName();
      _setLocationEditingValue();
      _setAddressGps();
      _notifyChange();
    });
  }

  LatLng latLong(){
    LatLng latLng; // 处理gps
    if(StringUtils.isNotEmpty(widget?.itemBean?.gps)){
      if(widget?.itemBean?.gps?.contains(",")){
        String beanGps = widget?.itemBean?.gps?.replaceAll("°E", "")?.replaceAll("°N", "");
        latLng = latLogDegree(beanGps);
      }
      setState(() { });
    }else if(StringUtils.isNotEmpty(widget?.defauleGps) && StringUtils.isEmpty(gps)){
      if(widget?.defauleGps?.contains(",")){
        latLng = latLogDegree(widget?.defauleGps);
      }
    }else if(StringUtils.isNotEmpty(gps)){
      if(gps?.contains(",")){
        String newGps = gps?.replaceAll("°E", "")?.replaceAll("°N", "");
        latLng = latLogDegree(newGps);
      }
      setState(() { });
    }
    return latLng;
  }

  LatLng latLogDegree(String gps){
    return LatLng(double.parse(gps?.split(",")[0]),double.parse(gps.split(",")[1]));
  }

  @override
  void dispose() {
    _locationEditingController?.dispose();
    _editingAddressController?.dispose();
    _editingBranchNameController?.dispose();
    if (_locationPlugin != null) _locationPlugin.dispose();
    super.dispose();
  }

  ///通知更新
  _notifyChange() {
    if (_uploadBean == null) {
      _uploadBean = CompanyRegisterUploadBean();
    }

    _uploadBean.setValue(
        locaiton: _locationEditingController?.text?.trim(),
        locationMap: _resultLocationMap,
        address: _editingAddressController?.text?.trim(),
        gps: _locationAddressController?.text
    );
    branchName = _editingBranchNameController?.text?.trim();
    _showBoutton();
  }

  void _setBranchName(){
    if(StringUtils.isEmpty(_editingBranchNameController?.text)){
      if(widget?.pageType == "编辑"){
        _editingBranchNameController?.text = widget?.itemBean?.branchname;
      }else{
        _editingBranchNameController?.text = widget?.companyNick;
      }
    }
  }

  void _setAddressGps(){
    if(StringUtils.isEmpty(_editingAddressController?.text)){
      _editingAddressController?.text = widget?.itemBean?.address;
    }
  }

  void _setLocationEditingValue() {
    if(StringUtils.isNotEmpty(widget?.itemBean?.gps)){
      if(widget?.itemBean?.gps?.contains("String gps")) widget?.itemBean?.gps = "";//处理错误数据
      gps = widget?.itemBean?.gps;
      _locationAddressController?.text =  widget?.itemBean?.gps;
    }else if(StringUtils.isNotEmpty(widget?.defauleGps) && StringUtils.isEmpty(gps)){
      gps = AddressAboutUtils.getLongitudeAndLatitude(widget?.defauleGps?.split(",")[1], widget?.defauleGps?.split(",")[0]);
      // _locationAddressController?.text = gps;
    }
    _locationEditingController?.text = _getAddressStr();
  }

  String _getAddressStr() {
    if(widget?.pageType!="编辑" && _resultLocationMap == null){
      return null;
    }
    province = widget?.itemBean?.addrProvince;
    city = widget?.itemBean?.addrCity;
    dirstrict = widget?.itemBean?.addrDistrict;
    if (_resultLocationMap == null || _resultLocationMap.isEmpty) {
      // _initLocation();
      if (province == city) {
        return "$province$dirstrict";
      } else {
        return "$province$city$dirstrict";
      }
    }else{
      if(StringUtils.isNotEmpty(_getGpsStr())){
        gps = _getGpsStr();
        // _locationAddressController?.text = gps;
        widget?.itemBean?.gps = gps;
      }
      addrCode = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sid;
      province = _resultLocationMap[CHOOSE_PROVINCE_KEY]?.sname;
      city = _resultLocationMap[CHOOSE_CITY_KEY]?.sname;
      dirstrict = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sname;
      if(StringUtils.isEmpty(dirstrict)){
        dirstrict = "";
      }
      if (province == city) {
        return "$province$dirstrict";
      } else {
        return "$province$city$dirstrict";
      }
    }
  }

  String _getGpsStr() {
    double latitude = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.latitude;
    double longitude = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.longitude;
    return AddressAboutUtils.getLongitudeAndLatitude(longitude?.toString(), latitude?.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: Color(0xFF191E31),
      body: Column(
        children: [
          _toTopBarWidget(),
          _toBranchNameWidget(),
          _toEditsWidget(),
          SizedBox(height: 30),
          _toBottomWidget(),
        ],
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "${widget?.pageType}地址",
      isShowBack: true,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      rightWidget: Visibility(
        visible: (widget?.size??0)>1,
        child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          child: Container(
            padding: EdgeInsets.only(top: 13, bottom: 13),
            child: Text(
              "删除",
              style: TextStyle(
                fontSize: 13,
                color: ThemeRepository.getInstance()
                    .getMinorRedColor_F95355(),
              ),
            ),
          ),
          onTap: ()async{
            if((widget?.itemBean?.allCnt ?? 0) != 0){
              CommonISeeDialog.navigatorPushDialog(context, title: "提示",
                  content:"该地址已关联显示屏，无法删除，如需删除请先更换显示屏所属地址");
              // content ="该地址下绑定的终端显示屏将失去所属地址，确定删除？";
              return;
            }
            String content = "确定删除该地址？";
            bool result =
            await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: content,
                cancelText: "取消",
                confirmText: "删除",
                confirmBgColor: ThemeRepository.getInstance()
                    .getMinorRedColor_F95355());
            if (result ?? false) {
              widget?.voidCallback?.call();
            }
          },
        ),
      ),
      isHideRightWidget: widget.pageType!="编辑",
    );
  }

  Widget _toBranchNameWidget(){
    return Column(
      children: [
        SizedBox(height: 10,),
        // Container(
        //   height: 30,
        //   alignment: Alignment.centerLeft,
        //   padding: EdgeInsets.only(top: 7, left:15, bottom: 6),
        //   child: Text(
        //     "分支机构名",
        //     style: TextStyle(
        //       fontSize: 12,
        //       color: ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C(),
        //     ),
        //   ),
        // ),
        Container(
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Container(
            alignment: Alignment.centerLeft,
            child: VgTextField(
              controller: _editingBranchNameController,
              keyboardType: TextInputType.text,
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                  fontSize: 14),
              decoration: new InputDecoration(
                  counterText: "",
                  hintText: "请输入",
                  border: InputBorder.none,
                  hintStyle: TextStyle(
                      fontSize: 14,
                      color: VgColors.INPUT_BG_COLOR,
                  )),
              inputFormatters: <TextInputFormatter> [
                LengthLimitingTextInputFormatter(20)
              ],
              maxLines: 1,
            ),
          ),
        ),
      ],
    );
  }

  Widget _toEditsWidget() {
    return Column(
      children: [
        SizedBox(height: 10,),
        // Container(
        //   height: 30,
        //   alignment: Alignment.centerLeft,
        //   padding: EdgeInsets.only(top: 7, left:15, bottom: 6),
        //   child: Text(
        //     "分支地址",
        //     style: TextStyle(
        //       fontSize: 12,
        //       color: ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C(),
        //     ),
        //   ),
        // ),
        GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: Container(
            // height: 50,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            child: Column(
              children: [
                _EditTextWithTitleWidget(
                  controller: _locationEditingController,
                  title: "所在区县",
                  hintText: "请选择",
                  isShowGoIcon: true,
                  toJumpCallback: () async {
                    HudUtils.showLoading(context,true);
                    LocationRepository.getInstance().init(callback: (success)async{
                      HudUtils.showLoading(context,false);
                      Map<String, ChooseCityListItemBean> result =
                          await ChooseCityPage.navigatorPush(context,
                          subLevel: 3, selected: _resultLocationMap);
                      if (result == null || result.isEmpty) {
                        return;
                      }
                      _resultLocationMap = result;
                      _setLocationEditingValue();
                    });
                  },
                ),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 15),
                  height: 1,
                  color: Color(0xFF3A3F50),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 15),
                  child: _EditTextWithTitleWidget(
                    controller: _locationAddressController,
                    title: "GPS位置",
                    hintText: "请选择",
                    isShowGoIcon: true,
                    visible:false,
                    toJumpCallback: () async {
                      RouterUtils.routeForFutureResult(context, PunchRuleLocationPage(latLng: latLong(),)).then((value){
                        if(value==null) return;
                        Map<String,dynamic> map = value;
                        gps = map["llat"];
                        gpsadress = map["title"];
                        // _resultLocationMap
                        //code为空待解决---
                        //  var transResult = VgLocationUtils.transLocationToMap(map);
                        //  if (transResult == null) {
                        //    return;
                        //  }
                        //  _resultLocationMap = transResult;
                        //  _setLocationEditingValue();
                        _locationAddressController?.text = gps;
                        widget?.itemBean?.gps = gps;
                        setState(() { });
                      });
                    },
                  ),
                ),
                Container(
                  margin: EdgeInsets.symmetric(horizontal: 15),
                  height: 1,
                  color: Color(0xFF3A3F50),
                ),
                Row(
                  children: [
                    Container(
                      margin: EdgeInsets.only(left: 4),
                      child: Text(
                        "*",
                        style: TextStyle(
                            color: Color(0xFFFF455E),
                            fontSize: 14
                        ),
                      ),
                    ),
                    SizedBox(width: 3),
                    Container(
                        width: 56,
                        margin: EdgeInsets.only(top: 14, bottom: 15),
                        alignment: Alignment.centerLeft,
                        child: Text("详细地址",
                            style: TextStyle(
                              fontSize: 14,
                              color: ThemeRepository.getInstance()
                                  .getTextMinorGreyColor_808388(),
                            ))),
                    Expanded(
                      flex: 1,
                      child: Container(
                          margin: EdgeInsets.only(left: 15),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Expanded(
                                  flex: 1,
                                  child: VgTextField(
                                    controller: _editingAddressController,
                                    keyboardType: TextInputType.text,
                                    style: TextStyle(
                                        color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                                        fontSize: 14),
                                    maxLimitLength: 30,
                                    decoration: new InputDecoration(
                                        counterText: "",
                                        hintText: "请输入",
                                        border: InputBorder.none,
                                        hintStyle: TextStyle(
                                            fontSize: 14,
                                            color: VgColors.INPUT_BG_COLOR)),
                                  )),
                            ],
                          )),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _toBottomWidget() {
    return InkWell(
      onTap: () async {
        if (intervalClick(2) ?? false) {
          return null;
        }
      },
      child: Container(
        height: 40,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 15),
          child: RaisedButton(
            onPressed: () async {
              if(StringUtils.isEmpty(gps)){
                List<String> gpsList = [];
                if(widget?.defauleGps?.contains(",")){
                  gpsList = widget?.defauleGps?.split(",");
                  gps = AddressAboutUtils.getLongitudeAndLatitude(gpsList[1]?.toString(), gpsList[0]?.toString());
                  // gps = "${gpsList[0]?.toString()}°E,${gpsList[1]?.toString()}°N";
                }else{
                  gps = widget?.defauleGps;
                }
              }
              if(widget.pageType=="编辑"){
                if(buttonFull){
                  viewModel.setEditCompanyBranchInfo(context,city,addrCode,dirstrict,province,_uploadBean?.address,branchName,
                      gps,gpsadress,widget?.itemBean?.cbid);
                  if(widget?.updateBranch != null){
                    CompanyBranchListInfoBean itemBean = widget?.itemBean;
                    itemBean.addrCity = city;
                    itemBean.addrCode = addrCode;
                    itemBean.addrDistrict = dirstrict;
                    itemBean.addrProvince = province;
                    itemBean.address = _uploadBean?.address;
                    itemBean.branchname = branchName;
                    itemBean.gps = gps;
                    itemBean.gpsaddress = gpsadress;
                    widget?.updateBranch?.call(itemBean);
                  }
                }else{
                  VgToastUtils.toast(context, "请完善资料");
                }

              }else{
                if(buttonFull){
                  viewModel.setEditCompanyBranchInfo(context,city,addrCode,dirstrict,province,_uploadBean?.address,branchName,
                      gps,gpsadress,"");
                }else{
                  if(StringUtils.isEmpty(_editingBranchNameController?.text??"")){
                    VgToastUtils.toast(context, "请输入地址名");
                  }else{
                    VgToastUtils.toast(context, "请输入详细地址");
                  }
                }
              }
              setState(() { });
            },
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20),
            ),
            color:buttonFull? ThemeRepository.getInstance().getPrimaryColor_1890FF() : Color(0xFF3A3F50),
            child: Container(
              height: 21,
              alignment: Alignment.center,
              child: Text(
                "保存",
                style: TextStyle(
                    fontSize: 15,
                    color:buttonFull? ThemeRepository.getInstance().getTextMainColor_D0E0F7() : ThemeRepository.getInstance().getHintGreenColor_5E687C()
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  //限制3秒内只能点击一次
  bool intervalClick(int needTime){
    // 防重复提交
    if(lastPopTime == null || DateTime.now().difference(lastPopTime) > Duration(seconds: needTime)){
      lastPopTime = DateTime.now();
      print("允许点击");
      return false;
    }else{
      // lastPopTime = DateTime.now(); //如果不注释这行,则强制用户一定要间隔2s后才能成功点击. 而不是以上一次点击成功的时间开始计算.
      print("请勿重复点击！");
      return true;
    }
  }

  void _showBoutton(){
    if(_locationEditingController?.text!=null && _locationEditingController?.text!=""
        && _editingAddressController?.text!=null && _editingAddressController?.text!=""
        && _editingBranchNameController?.text != null && _editingBranchNameController?.text != ""){
      buttonFull = true;
    }else {
      buttonFull = false;
    }
    setState(() { });
  }
}


/// 带标题的编辑框
///
/// @author: zengxiangxi
/// @createTime: 1/5/21 2:29 PM
/// @specialDemand:
class _EditTextWithTitleWidget extends StatefulWidget {
  final String title;

  final String hintText;

  final bool isShowGoIcon;

  final VoidCallback toJumpCallback;

  final TextEditingController controller;

  final int maxZHCharLimit;

  final bool visible;

  const _EditTextWithTitleWidget(
      {Key key,
        this.title,
        this.hintText,
        this.isShowGoIcon = false,
        this.toJumpCallback,
        this.controller, this.maxZHCharLimit, this.visible})
      : super(key: key);

  @override
  _EditTextWithTitleWidgetState createState() =>
      _EditTextWithTitleWidgetState();
}

class _EditTextWithTitleWidgetState extends State<_EditTextWithTitleWidget> {
  FocusNode _focusNode;

  ValueNotifier<bool> _isShowFocusLineNotifier;

  @override
  void initState() {
    super.initState();
    _isShowFocusLineNotifier = ValueNotifier(false);
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode?.hasFocus ?? false) {
        _isShowFocusLineNotifier.value = true;
      } else {
        _isShowFocusLineNotifier.value = false;
      }
    });
  }

  @override
  void dispose() {
    _focusNode?.dispose();
    _isShowFocusLineNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Container(
          height: 45,
          padding: const EdgeInsets.only(right: 15),
          child: Row(
            children: <Widget>[
              Visibility(
                visible: widget?.visible ?? true,
                child: Container(
                  margin: EdgeInsets.only(left: 4,right: 3),
                  child: Text(
                    "*",
                    style: TextStyle(
                        color: Color(0xFFFF455E),
                        fontSize: 14
                    ),
                  ),
                ),
              ),
              Container(
                width: 71,
                alignment: Alignment.centerLeft,
                child: Text(
                  widget.title ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getTextMinorGreyColor_808388(),
                    fontSize: 14,
                  ),
                ),
              ),
              Expanded(
                child: VgTextField(
                  controller: widget?.controller,
                  maxLines: 1,
                  focusNode: _focusNode,
                  readOnly: widget.toJumpCallback != null ? true : false,
                  onTap: () {
                    if (widget.toJumpCallback != null) {
                      widget.toJumpCallback();
                    }
                  },
                  maxLimitLength: widget?.maxZHCharLimit,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    counterText: "",
                    contentPadding: const EdgeInsets.only(bottom: 2),
                    hintText: widget.hintText ?? "",
                    hintStyle: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 14),
                  ),
                  style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance()
                          .getTextMainColor_D0E0F7()),
                ),
              ),
              Opacity(
                opacity: widget.isShowGoIcon ? 1 : 0,
                child: Container(
                    padding: const EdgeInsets.only(left: 5),
                    child: Image.asset(
                      "images/index_arrow_ico.png",
                      width: 6,
                    )),
              )
            ],
          ),
        ),
      ],
    );
  }
}
